package com.jnu.bookstore;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MapViewFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MapViewFragment extends Fragment {

    private  MapView mapView;
    public static final int WHAT_DATA_OK = 1000;



    public MapViewFragment() {
        // Required empty public constructor
    }

    public static MapViewFragment newInstance() {
        MapViewFragment fragment = new MapViewFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
    }
    public static Bitmap imageScale(Bitmap bitmap, int dst_w, int dst_h) {
        int src_w = bitmap.getWidth();
        int src_h = bitmap.getHeight();
        float scale_w = ((float) dst_w) / src_w;
        float scale_h = ((float) dst_h) / src_h;
        Matrix matrix = new Matrix();
        matrix.postScale(scale_w, scale_h);
        Bitmap dstbmp = Bitmap.createBitmap(bitmap, 0, 0, src_w, src_h, matrix,
                true);
        return dstbmp;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_map_view, container, false);
        mapView=rootView.findViewById(R.id.bmapView);

        LatLng cenpt = new LatLng(22.257704,113.542914);
        LatLng liabray = new LatLng(22.255086,113.542474);
        Bitmap bitmap= imageScale(BitmapFactory.decodeResource(getResources(),R.drawable.jinan),300,300);
        BitmapDescriptor bitmapDescriptor= BitmapDescriptorFactory.fromBitmap(bitmap);
        BitmapDescriptor bitmap2 = BitmapDescriptorFactory.fromResource(R.drawable.jinann);

       Bundle mBundle= new Bundle();
        mBundle.putInt("id",1);
        MarkerOptions mark=new MarkerOptions();
        mark.position(cenpt).icon(bitmapDescriptor);
        Overlay marker= mapView.getMap().addOverlay(mark);
        marker.setExtraInfo(mBundle);

       Bundle mBundle2 = new Bundle();
        mBundle2.putInt("id",2);
        TextOptions textOptions = new TextOptions()
                .bgColor(0xAAFFFF00)  //設置文字覆盖物背景颜色
                .fontSize(40)  //设置字体大小
                .fontColor(0xFFFF00FF)// 设置字体颜色
                .text("暨南大学图书馆")  //文字内容
                .rotate(0)  //设置文字的旋转角度
                .position(liabray);
        mapView.getMap().addOverlay(textOptions);//地图上添加mark

        Handler handler=new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if(msg.what==WHAT_DATA_OK)
                {
                    String content= msg.getData().getString("data");
                    if(null!=content) {
                        try {
                            JSONObject jsonObject = new JSONObject(content);
                            JSONArray shops=jsonObject.getJSONArray("shops");
                            for(int index=0;index<shops.length();index++)
                            {
                                JSONObject shop=shops.getJSONObject(index);
                                Log.i("test",shop.getDouble("latitude")+"");
                                LatLng centerPoint = new LatLng(shop.getDouble("latitude"),shop.getDouble("longitude"));
                                MarkerOptions markerOption = new MarkerOptions().icon(bitmap2).position(centerPoint);
                                Marker marker = (Marker) mapView.getMap().addOverlay(markerOption);
                                OverlayOptions textOption = new TextOptions().bgColor(0xAAFFFF00).fontSize(50)
                                        .fontColor(0xFFFF00FF).text(shop.getString("name")).rotate(0).position(centerPoint);
                                mapView.getMap().addOverlay(textOption);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                }

            }
        };
        Runnable runnable= new Runnable() {
            @Override
            public void run() {
                try{
                    URL url=new URL("http://file.nidama.net/class/mobile_develop/data/bookstore.json");
                    HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
                    httpURLConnection.setUseCaches(false);
                    httpURLConnection.connect();
                    if(httpURLConnection.getResponseCode()==HttpURLConnection.HTTP_OK)
                    {

                        InputStream inputStream= httpURLConnection.getInputStream();
                        InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
                        BufferedReader bufferedReader=new BufferedReader(inputStreamReader);

                        String line="";
                        StringBuffer stringBuffer=new StringBuffer();
                        while( null!=(line=bufferedReader.readLine())) {
                            stringBuffer.append(line);
                        }

                        Message message=new Message();
                        message.what= WHAT_DATA_OK;
                        Bundle bundle=new Bundle();
                        bundle.putString("data",stringBuffer.toString());
                        message.setData(bundle);

                        handler.sendMessage(message);
                        Log.i("test", "onCreateView: "+stringBuffer.toString());
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        };
        new Thread(runnable).start();
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.zoom(18.0f).target(cenpt);
        mapView.getMap().setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));


//添加marker点击事件的监听
        mapView.getMap().setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {//设置图标点击事件
            @Override
            public boolean onMarkerClick(Marker marker) {
               Bundle bundle = marker.getExtraInfo();
                int id = bundle.getInt("id");
                Toast ts;
               switch (id) {
                    case 1:
                    ts = Toast.makeText(getActivity(),
                            "欢迎来到暨南大学", Toast.LENGTH_SHORT);
                        ts.show();
                   break;

                }

                return true;
            }
        });

        return rootView;
    }

    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mapView. onResume ()，实现地图生命周期管理
        mapView.onResume();
    }
    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mapView. onPause ()，实现地图生命周期管理
        mapView.onPause();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mapView.onDestroy()，实现地图生命周期管理
        mapView.onDestroy();
    }
}